//提交申请弹窗
import React, { useState, useEffect } from "react";
import { Form, Input, InputNumber, Button, Menu, Dropdown, Popconfirm, message, Modal, Typography, Tooltip } from "antd";
import CommonLoading from "@/components/CommonLoading";
import CommonModal from "@/components/CommonModal";
import CommonTable from "@/components/CommonTable";
import CommonGoodsImg from "@/components/CommonGoodsImg";
import CommonPagination from "@/components/CommonPagination";
import FuzzyQueryStore from "@/components/FuzzyQueryStore";
import AddGoodsModal from "./AddModal";
import { customTrimFunc } from "@/utils/utils.jsx";
import { getzjfstoreList, deletePriceOp, getPriceList, postApplyDataOp } from "../service";
import styles from "../index.module.less";
import { cloneDeep, isEmpty } from "lodash";

const { Paragraph } = Typography;

const initPagination = {
	current: 1,
	total: 0,
	pageSize: 100,
	showSizeChange: true,
	showQuickJumper: true
}; //分页

export default ({ visible, handleOk, handleCancel }) => {
	const [form] = Form.useForm();
	const [query, setQuery] = useState({});
	const [data, setData] = useState([]);
	const [pagination, setPage] = useState({ ...initPagination }); //分页
	const [loading, setLoading] = useState(false);
	const [showStatus, setShow] = useState(false); //1 添加商品modal

	const [stageObj, setObj] = useState({}); //填写的会员价存储映射
	const [updateKey, setUpdateKey] = useState(0); //删除行更新key

	useEffect(() => {
		if (visible) {
			getTableDataFunc({ size: 100, current: 1 });
		}
	}, [visible]);

	useEffect(() => {
		if (updateKey) {
			getTableDataFunc({ ...query, current: 1, size: pagination.pageSize });
		}
	}, [updateKey]);

	//获取表格数据
	const getTableDataFunc = async params => {
		params.verifyStatus = 0;
		setLoading(true);
		const { data, success } = await getPriceList(customTrimFunc(params));
		if (success) {
			const { records = [], total } = data;
			records.map((item, index, _self) => {
				let stage = 0;
				item.goodsPriceVos.map(items => {
					stage += items.goodsColorPriceVos.length;
				});
				_self[index].stage = stage;
			});
			const pageTableData = [];
			records.map((item, index) => {
				item.goodsPriceVos.map((items, indexs) => {
					let rowSpan_sku = items.goodsColorPriceVos.length;
					items.goodsColorPriceVos.map((child, childs) => {
						pageTableData.push({
							...item,
							...child,
							index: index + 1,
							size: items.size,
							goodsPriceVos: null,
							stage: null,
							rowSpan_spu: indexs || childs ? 0 : item.stage,
							rowSpan_sku: childs ? 0 : rowSpan_sku
						});
					});
				});
			});
			if (!isEmpty(stageObj)) {
				pageTableData.map((item, index, _self) => {
					const { storeName = "", commonGoodsName = "", size = "", colors = [] } = item;
					const key = storeName + commonGoodsName + size + colors.join("");
					item.vipPrice = stageObj[key] ? stageObj[key] : 0;
				});
			}
			setData(pageTableData);
			// console.log(pageTableData,'apply')
			const { size, current } = params;
			setPage({
				current,
				total,
				pageSize: size,
				showSizeChange: true,
				showQuickJumper: true
			});
		}
		let timer = setTimeout(() => {
			setLoading(false);
			clearTimeout(timer);
			timer = null;
		}, 300);
	};

	// 搜索
	const onFinish = values => {
		setQuery(values);
		setObj({});
		getTableDataFunc({ ...values, current: 1, size: pagination.pageSize });
	};

	// 重置
	const ApplyModalReset = () => {
		setQuery({});
		setObj({});
		getTableDataFunc({ current: 1, size: pagination.pageSize });
		form.resetFields();
	};

	// 输入更改价格
	const updatePrice = (value, index) => {
		data[index].vipPrice = formatPrice(value);
		setData(data);
	};

	// 失焦验证输入价格
	const checkPrice = (record, index) => {
		const { goodPrice, vipPrice = 0 } = data[index];
		//处理提示
		const arr = cloneDeep(data);
		if (goodPrice <= vipPrice) {
			arr[index].showTips = true;
		} else {
			arr[index].showTips = false;
		}
		//更新缓存
		const { storeName = "", commonGoodsName = "", size = "", colors = [] } = record;
		const key = storeName + commonGoodsName + size + colors.join("");
		stageObj[key] = vipPrice;

		setData(arr);
		setObj({ ...stageObj });
	};

	// 删除行整合数据
	const deleteApplyData = async (record, index) => {
		const ids = [];
		record.goodsPriceVerifyVos.map(function (item) {
			ids.push(item.id);
		});
		setLoading(true);
		const res = await deletePriceOp(ids);
		if (res.success) {
			message.success("操作成功");
			if (!isEmpty(stageObj)) {
				const { storeName = "", commonGoodsName = "", size = "", colors = [] } = record;
				const key = storeName + commonGoodsName + size + colors.join("");
				stageObj[key] = undefined;
				setObj(stageObj);
			}
			setUpdateKey(updateKey + 1);
		}
		let timer = setTimeout(() => {
			setLoading(false);
			clearTimeout(timer);
			timer = null;
		}, 300);
	};

	// 提交申请
	const postApply = async () => {
		if (data.length) {
			let bool;
			const params = [];
			data.map(items => {
				if (!items.vipPrice || items.showTips || items.vipPrice >= items.goodPrice) {
					bool = true;
					items.showTips = true;
				}
				const ids = [];
				items.goodsPriceVerifyVos.map(function (child) {
					ids.push(child.id);
				});
				params.push({
					ids,
					vipPrice: items.vipPrice
				});
			});
			if (bool) {
				Modal.info({ centered: true, content: "请先正确填写会员价" });
			} else {
				const res = await postApplyDataOp(params);
				if (res.success) {
					message.success("提交申请成功，已进入待审核状态");
					handleOk();
					onCancel();
				}
			}
		} else {
			message.info("暂无数据可支持该操作，可先添加商品");
		}
	};

	//format 会员价输入
	const formatPrice = e => {
		if (e && e.toString().indexOf(".") > -1) {
			const arr = e.toString().split(".");
			return arr[0] + "." + arr[1].slice(0, 2);
		} else {
			return e;
		}
	};

	const columns = [
		{
			title: "#",
			dataIndex: "index",
			fixed: "left",
			width: 40,
			render: (text, record) => {
				return {
					children: text,
					props: {
						rowSpan: record.rowSpan_spu
					}
				};
			}
		},
		{
			title: "供应商",
			dataIndex: "storeName",
			key: "storeName",
			width: 120,
			render: (text, record) => {
				return {
					children: text,
					props: {
						rowSpan: record.rowSpan_spu
					}
				};
			}
		},
		{
			title: "商品",
			dataIndex: "commonGoodsName",
			key: "commonGoodsName",
			width: 200,
			render: (text, record) => {
				return {
					children: (
						<div className="flex" style={{ margin: "5px 0" }}>
							<CommonGoodsImg
								img={record.goodsImage}
								storeId={record.zjfStorePk}
								goodsId={record.zjfGoodsCommonPk}
								size="48x48"
								width="48"
							/>
							<div style={{ marginLeft: "8px", display: "flex", justifyContent: "center", alignItems: "center" }}>
								<Tooltip title={record.commonGoodsName}>
									<Paragraph ellipsis={{ rows: 2 }} style={{ margin: 0 }}>
										{record.commonGoodsName}
									</Paragraph>
								</Tooltip>
							</div>
						</div>
					),
					props: {
						rowSpan: record.rowSpan_spu
					}
				};
			}
		},
		{
			title: "尺码/规格",
			dataIndex: "size",
			key: "size",
			width: 180,
			render: (text, record) => {
				return {
					children: text,
					props: {
						rowSpan: record.rowSpan_sku
					}
				};
			}
		},
		{
			title: "颜色",
			dataIndex: "name1",
			key: "name1",
			width: 120,
			render: (text, { colors = [] }) => {
				if (colors.length > 1) {
					const menu = (
						<Menu>
							{colors.map(item => (
								<Menu.Item key={item}>{item}</Menu.Item>
							))}
						</Menu>
					);
					return (
						<Dropdown overlay={menu} placement="bottomCenter" overlayClassName={styles.dropdown}>
							<a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
								同价格颜色({colors.length})
							</a>
						</Dropdown>
					);
				}
				return colors[0];
			}
		},
		{
			title: "商城价",
			dataIndex: "goodPrice",
			key: "goodPrice",
			width: 100,
			render: text => <span className="common-color9">￥{text}</span>
		},
		{
			title: "会员价",
			dataIndex: "vipPrice",
			key: "vipPrice",
			width: 100,
			render: (text, record, index) => (
				<>
					<InputNumber
						defaultValue={record.vipPrice ? record.vipPrice : ""}
						onChange={value => updatePrice(value, index)}
						onBlur={() => checkPrice(record, index)}
						min={0}
						step={0.01}
						style={{ color: "#0165D5" }}
						formatter={formatPrice}
					/>
					{record?.vipPrice >= record.goodPrice ? (
						<p style={{ color: "red", margin: "8px 0 0 0", fontSize: 12, textAlign: "center" }}>必须小于商城价</p>
					) : null}
				</>
			)
		},
		{
			title: "操作",
			dataIndex: "name2",
			key: "name2",
			fixed: "right",
			width: 80,
			render: (text, record, index) => (
				<Popconfirm title="确定删除吗？" okText="确定" cancelText="取消" onConfirm={() => deleteApplyData(record, index)}>
					<Button type="link">删除</Button>
				</Popconfirm>
			)
		}
	];

	//表格props
	const applyTableProps = {
		columns,
		data,
		size: "small",
		scroll: { x: 927, y: 420 }
	};

	//分页props
	const pageProps = {
		pagination,
		handleChange: function (current, size) {
			if (size != pagination.pageSize) {
				//pageSize改变时,页码重置为1
				getTableDataFunc({ ...query, size, current: 1 });
			} else {
				getTableDataFunc({ ...query, size, current });
				// setObj({})
			}
		}
	};

	//取消操作
	const onCancel = () => {
		handleCancel();
		setQuery({});
		setData([]);
		setObj({});
		setPage({ ...initPagination });
		form.resetFields();
	};

	// 添加弹窗
	const AddModalProps = {
		visible: showStatus,
		handleOk() {
			setUpdateKey(updateKey + 1);
		},
		handleCancel() {
			setShow(false);
		}
	};

	return (
		<>
			<CommonModal
				title="申请会员价"
				visible={visible}
				onCancel={onCancel}
				width="920px"
				footer={
					<>
						<Button onClick={onCancel}>取消</Button>
						<Button type="primary" onClick={() => postApply()}>
							提交申请
						</Button>
					</>
				}
			>
				<Form layout={"inline"} onFinish={onFinish} form={form} style={{ marginBottom: 16 }} name="applyModalForm">
					<Form.Item label="供应商" name="zjfStorePk" rules={[{ required: true }]}>
						<FuzzyQueryStore width={200} queryData={getzjfstoreList} />
					</Form.Item>

					<Form.Item label="商品" name="zjfGoodsCommonName">
						<Input style={{ width: 200 }} />
					</Form.Item>

					<Form.Item>
						<Button htmlType="submit" type="primary">
							查询
						</Button>
						&nbsp;&nbsp;
						<Button onClick={() => ApplyModalReset()}>重置</Button>
					</Form.Item>
				</Form>

				<div className="common-table-header-btn">
					<Button onClick={() => setShow(1)}>添加商品</Button>
				</div>

				<CommonTable {...applyTableProps} />

				<div style={{ height: 28, marginTop: "12px", position: "absoluted", right: "40px", bottom: 0 }}>
					<span style={{ float: "right" }}>
						<CommonPagination {...pageProps} />
					</span>
				</div>
			</CommonModal>
			<AddGoodsModal {...AddModalProps} />
			<CommonLoading loading={loading} />
		</>
	);
};
